今天我們正式來學習 Vue 基本的模板語法啦!
使用的是 Mustache 語法,即雙大括號 {{ }}。
我們來看看實際例子~

在 Mustache.vue 中,我們可以這樣定義:
<script setup>
const msg = "Mustache message";
</script>
<template>
  <div>{{ msg }}</div>
</template>
而這段程式碼做了以下的事情:
const msg = "Mustache message" 定義了一個名為 msg 的變數,其值為 "Mustache message"。<div>{{ msg }}</div> 使用文本插值的方式,將 msg 屬性的值插入到 HTML 中,這裡會顯示 "Mustache message"。而在它的父組件 App.vue 中,我們可以這樣引入和使用子組件:
<script setup>
import mustache from "./components/Mustache.vue";
</script>
<template>
  <main>
    <mustache />
  </main>
</template>
而這段程式碼做了以下的事情:
import mustache from Mustache.vue 將 Mustache.vue 組件引入,且在這個檔案裡可以用 mustache 來代表引入的該組件。<mustache /> 作為自定義標籤,將 Mustache 組件渲染到父組件中。於是我們在瀏覽器上會看到:
使用的是 v-html 語法。
當我們想要插入「html code」時,可以使用這個方法。
{{ }} 和 v-html 不同的地方是:
{{ }} 定義的資料會被以「純文字」渲染。v-html 屬性定義的值會被以「html code」渲染。
我們在 vHtml.vue 這個子組件定義了兩個 div:
<div>{{ rawHtml }}</div>:以 {{ }} 語法定義。<div v-html="rawHtml"></div>:以 v-html 語法定義。然後在 App.vue 父組件中將 vHtml 子組件 import 到其中,並指定 rawHtml 屬性值為 "<strong>This is where I can put the HTML code</strong>"。
在瀏覽器上會看到:
第一行 為:使用 {{ }} 定義的值 >> 被解析成「純文字」。
第二行 為:使用 v-html 定義的值 >> 被解析成「html code」,所以就吃到了我們寫的 strong 粗體樣式(撒花)!!
今天我們先認識最基本的兩種模板語法,明天我們來看看「屬性綁定」
https://github.com/Jamixcs/2024iThome-jamixcs/tree/main/src/components/day7